#!/usr/bin/env python
# Copyright (C) 2008  Mohd Izhar Firdaus <izhar _at_ fedoraproject.org>
#
# This program is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# This program is distrubuted in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
#
# http://www.gnu.org/copyleft/gpl.html


import re, getopt, sys
from subprocess import Popen, PIPE

def usage():
    print """
 Usage: %s [OPTIONS]

 This script will automatically find for packages which 
 one or more of its files does not match the information
 stored in the RPMdb. 

 -h : show this menu
 -v : be verbose

 This script excludes packages which only have its config files
 changed and packages which its files only does not match the
 stored mtime.
    """ % (sys.argv[0])

def main():
    verbose=False
    try:
       opts,args = getopt.getopt(sys.argv[1:],'hv',['--help'])
    except getopt.GetoptError,err:
       print str(err)
       usage()
       sys.exit(2)
    
    for o,a in opts:
        if '-h' in o or '--help' in o:
           usage()
           sys.exit(0)
        if '-v' in o: verbose=True
    
    strout = ""
    # find non-config files which returns problem
    p = Popen(['rpm','-Va','--nomtime'],stdout=PIPE)
    while True:
        o = p.stdout.readline()
        if o == '' and p.poll() != None: break
        if verbose: print o.strip()
        strout = strout + o

    output1 = strout.split('\n')

    regex = re.compile('........   (.*)')
    regex2 = re.compile('(.*)\(.*\)')
    output2 = []
    for o in output1:
        r = regex.match(o)
        if r:
           filestr = r.group(1)
           r2 = regex2.match(filestr)
           if r2:
              filestr = r2.group(1)
           output2.append(filestr)

    # find which RPM the file belongs to
    output3 = []
    for o in output2:
        p = Popen(['rpm','-qf',o.strip(),'--queryformat','%{name}\n'],stdout=PIPE)
        p.wait()
        out = p.stdout.readline()
        if verbose: print out.replace('\n','')
        output3.append(out)

    # print them out
    if not verbose:
        o = list(set(output3))
        o.sort()
        print ''.join(o)

if __name__ == "__main__":
   main()
